<template>
    <n-form
        ref="formRef"
        label-placement="left"
        :label-width="80"
        :model="form"
        :rules="rules"
    >
        <n-grid cols="2" x-gap="24">
            <n-gi>
                <n-card title="基础信息">
                    <n-form-item label="姓名" path="name">
                        <n-input v-model:value="form.name" placeholder="请输入用户姓名" />
                    </n-form-item>
                    <n-form-item label="编号" path="sn">
                        <n-input
                            v-model:value="form.sn"
                            placeholder="请输入用户编号或工号"
                        />
                    </n-form-item>
                    <n-form-item label="性别" path="sex">
                        <jb-radio-group
                            v-model:value="form.sex"
                            :value-to-number="true"
                            url="/api/admin/dictionary/options?typeKey=sex"
                        ></jb-radio-group>
                    </n-form-item>
                    <n-form-item label="年龄" path="age">
                        <n-input v-model:value="form.age" placeholder="请输入用户年龄" />
                    </n-form-item>
                    <n-form-item label="手机号" path="phone">
                        <n-input
                            v-model:value="form.phone"
                            placeholder="请输入用户手机号"
                        />
                    </n-form-item>
                    <n-form-item label="E-Mail" path="email">
                        <n-input
                            v-model:value="form.email"
                            placeholder="请输入用户邮箱"
                        />
                    </n-form-item>
                </n-card>
            </n-gi>
            <n-gi>
                <n-card title="账号配置">
                    <n-form-item label="头像" path="avatar">
                        <jb-avatar v-model:src="form.avatar" :upload="true"></jb-avatar>
                    </n-form-item>
                    <n-form-item label="用户名" path="username">
                        <n-input
                            v-model:value="form.username"
                            placeholder="请输入登录用户名"
                        />
                    </n-form-item>
                    <n-form-item v-if="!props.id" label="密码" path="password">
                        <n-input
                            v-model:value="form.password"
                            type="password"
                            placeholder="请输入登录密码"
                        />
                    </n-form-item>
                    <n-form-item label="角色" path="roles">
                        <jb-tree-select
                            v-model:value="form.roles"
                            checkable
                            cascade
                            check-strategy="child"
                            url="/api/admin/role/datas"
                            multiple
                        ></jb-tree-select>
                    </n-form-item>
                    <n-form-item v-if="config.deptEnable" label="部门" path="deptId">
                        <jb-tree-select
                            v-model:value="form.deptId"
                            url="/api/admin/dept/enableOptions"
                        ></jb-tree-select>
                    </n-form-item>
                    <n-form-item v-if="config.postEnable" label="岗位" path="posts">
                        <jb-select
                            v-model:value="form.posts"
                            url="/api/admin/post/options"
                            multiple
                        ></jb-select>
                    </n-form-item>
                </n-card>
            </n-gi>
        </n-grid>
    </n-form>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import XEUtils from 'xe-utils'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        id?: string
    }>(),
    {
        id: ''
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface UserType {
    id: string
    name: string
    sn: string
    sex: number
    age: string
    phone: string
    email: string
    username: string
    password: string
    roles: string[]
    avatar: string
    deptId: string
    posts: string[]
}
const form = useResetableData<UserType>({
    id: '',
    name: '',
    sn: '',
    sex: 1,
    age: '',
    email: '',
    phone: '',
    username: '',
    password: '',
    roles: [],
    avatar: '',
    deptId: '',
    posts: []
})
const rules: FormRules = {
    name: new Rules().required('请输入姓名').value,
    username: new Rules().required('请输入用户名').value,
    sn: new Rules().minLength(4).value,
    sex: new Rules().required('请选择用户性别').value,
    password: new Rules().required('请选择密码').value,
    roles: new Rules().required('请选择角色').value,
    age: new Rules()._pint().maxLength(3).value,
    email: new Rules().email().value,
    phone: new Rules().phone().value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()

    let url = props.id ? '/api/admin/user/update' : '/api/admin/user/save'
    let data: any = XEUtils.clone(form, true)
    if (props.id) {
        delete data['password']
    }
    data.roles = data.roles.join(',')
    data.posts = data.posts.join(',')
    let res = await JBoltApi.tryPost(url, data)
    return res.data
}

function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/user/${props.id}`).then(({ error, result }) => {
        if (error) return
        let { user } = result.data
        user.roles = user.roles?.split(',') ?? []
        user.posts = user.posts?.split(',') ?? []
        form._reset(user)
    })
}

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})

/** 表单相关 end */

/** 部门岗位相关配置 start */
const config = reactive({
    postEnable: false,
    deptEnable: false
})

async function loadConfig() {
    let res = await JBoltApi.tryGet(
        '/api/admin/globalConfig/getByKeys?keys=SYSTEM_DEPT_ENABLE,SYSTEM_POST_ENABLE'
    )
    config.postEnable = res.data['SYSTEM_POST_ENABLE']
    config.deptEnable = res.data['SYSTEM_DEPT_ENABLE']
}
onMounted(() => {
    loadConfig()
})

/** 部门岗位相关配置 end */
</script>
<style scoped></style>
